<?php
class PostViewAction extends FrontendAction
{
	public function __construct()
	{
		parent::__construct();
		$this->responseType = 'tpl';
		$this->layout = 'index';
		$this->data['menu']		= 'post';
	}

	public function execute()
	{
		$id		= $this->context->get('id');
		if(!is_numeric($id) || $id<=0)
		{
			$this->layout 	= 'result';
			$this->code		= 400;
			return;
		}
		
		$postService	= new PostService();
		$postInfo		= $postService->get($id);
		if(!$postInfo)
		{
			$this->layout 	= 'result';
			$this->code		= 400;
			return;
		}
		
		//更新浏览量
		$postService->addVisitNum($id,1);
		$postInfo['visit_num']++;
		
		//获取用户信息
		$userService	= C('UserService');
		if($postInfo['user_id']>0)
		{
			$postInfo['user']	= $userService->get($postInfo['user_id']);
		}
		
		//获取评论
		$page			= $this->getPage();
		$ltConfig		= C('LtConfig');
		$pagerConfig	= $ltConfig->get('pagination.pager');
		$pageSize		= 50;
		$pagerConfig['per_page']		= $pageSize;
		$pagerConfig['num_links_show']	= 10;
		$ltConfig->addConfig(array('pagination.pager'=>$pagerConfig));
		
		$num 			= $pageSize;
		$start	 		= ($page-1) * $pageSize;
		$result			= $postService->getList(array('pid'=>$id),'id ASC',$start,$num);
		$totalNum		= $result['count'];
		$postList		= $result['rows'];
		//获取用户信息
		if($postList)
		{
			$userIds	= array();
			foreach($postList as $lv)
			{
				if($lv['user_id']>0)
				{
					$userIds[]	= $lv['user_id'];
				}
			}
			if(!empty($userIds))
			{
				$userList	= $userService->getUserListByIds($userIds);
				if($userList)
				{
					$users	= C('CommonFunction')->groupData($userList,array('id'));
					foreach($postList as &$lv)
					{
						if($lv['user_id']>0)
						{
							$lv['user']	= $users[$lv['user_id']];
						}
					}
				}
			}
		}
		if(empty($postList))
		{
			$postList	= array();
		}
		array_unshift($postList,$postInfo);
		$this->data['page']			= $page;
		$this->data['totalNum']		= $totalNum;
		$this->data['postList']		= $postList;
		$baseUrl 	= C('LtUrl')->generate('Post', 'View', array('id'=>$id,'p' => ':page'));
		
		$pagination 	= new PiscesPagination;
		$pagination->init();
		$this->data['pages'] = $pagination->pager($page, $totalNum, $baseUrl);
		
		//关联商品
		$this->data['related']	= C('ProductRelatedService')->get($id);
		
		//广告
		$adService		= new AdService();
		$adList			= $adService->getAdList(true,array('position'));
		$this->data['adList']	= $adList;
		
		$seoTitle		= $postInfo['title'].'-'.$this->data['site']['site_name'];
		$seoKeyword		= $postInfo['tag'];
		
		$this->data['seo']['title']			= $seoTitle;
		$this->data['seo']['keyword']		= $seoKeyword;
	}
}
